package com.ekuaitu.kuaitustaff.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.GeneralBasicParams;
import com.baidu.ocr.sdk.model.GeneralResult;
import com.baidu.ocr.sdk.model.OcrRequestParams;
import com.baidu.ocr.sdk.model.OcrResponseResult;
import com.ekuaitu.kuaitustaff.R;
import com.ekuaitu.kuaitustaff.base.BaseActivity;
import com.ekuaitu.kuaitustaff.bean.LicenseTagBean;
import com.ekuaitu.kuaitustaff.bean.TextScanTagBean;
import com.ekuaitu.kuaitustaff.utils.AppManager;
import com.ekuaitu.kuaitustaff.utils.Logger;
import com.ekuaitu.kuaitustaff.utils.NetUtils;
import com.ekuaitu.kuaitustaff.utils.SDCardUtils;
import com.ekuaitu.kuaitustaff.utils.ThreadPool;
import com.ekuaitu.kuaitustaff.utils.ToastUtils;
import com.ekuaitu.kuaitustaff.utils.camera.CameraThreadPool;
import com.ekuaitu.kuaitustaff.utils.camera.CameraView;
import com.ekuaitu.kuaitustaff.utils.camera.ICameraControl;
import com.ekuaitu.kuaitustaff.utils.camera.MaskView;
import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class RecogCarTextActivity extends BaseActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
    @BindView(R.id.ll_scan_light)
    LinearLayout llScanLight;
    @BindView(R.id.qr_code_header_back)
    ImageView qrCodeHeaderBack;
    @BindView(R.id.iv_scan_light)
    ImageView ivScanLight;
    @BindView(R.id.camera)
    CameraView cameraView;
    @BindView(R.id.tv_take_picture)
    TextView takePicture;
    @BindView(R.id.tv_tip)
    TextView tvTip;


    private Context mContext = this;
    private String number;
    private SensorManager sensorManager;
    private boolean isLightOn = false;
    private File outputFile;

    @Override
    public int getLayoutId() {
        return R.layout.activity_recognize_plate;
    }


    @Override
    public void initData() {
        initLightSenser();
    }

    @Override
    public void initView() {
        //设置启动界面全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);

        int maskType = MaskView.MASK_TYPE_NONE;
        cameraView.setMaskType(maskType, this);
        takePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MobclickAgent.onEvent(mContext, "tapScanTag");
                showLoadingDialog();
                takephoto();
            }
        });
    }

    private void takephoto() {
        try {
            takePicture.setClickable(false);
            outputFile = new File(SDCardUtils.getSDCardPrivateCacheDir(mContext) + File.separator + "ocr.jpg");
            cameraView.takePicture(outputFile, takePictureCallback);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private CameraView.OnTakePictureCallback takePictureCallback = new CameraView.OnTakePictureCallback() {
        @Override
        public void onPictureTaken(final Bitmap bitmap) {
            try {
                Luban.with(mContext)
                        .load(outputFile)  //传入要压缩的图片
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {
                            }

                            @Override
                            public void onSuccess(File file) {
                                takePicture.setClickable(true);
                                gotPicture(file);
                            }

                            @Override
                            public void onError(Throwable e) {
                                dismissLoadingDialog();
                            }
                        }).launch();    //启动压缩
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    private void gotPicture(File file) {
        if (file == null) {
            MobclickAgent.onEvent(mContext, "tapScanTagFailed");
            cameraView.start();
            dismissLoadingDialog();
            ToastUtils.makeText(mContext, "识别失败，请重试", ToastUtils.LENGTH_SHORT).show();
            return;
        }
        if (!NetUtils.isNetworkAvailable(mContext)) {
            cameraView.start();
            dismissLoadingDialog();
            ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
            return;
        }
        if (true) {
            startOcr(file);
        } else {
            cameraView.start();
            dismissLoadingDialog();
            ToastUtils.makeText(mContext, "今日扫描次数过多。", ToastUtils.LENGTH_SHORT).show();
        }
    }

    private void startOcr(File file) {
        //最初的拍照结果在Camera1 takePictureInternal()
        ThreadPool.execute(() -> {
            if (getIntent().getIntExtra("ocr_type", 0) == 0) {
                // 车牌识别参数设置
                OcrRequestParams param = new OcrRequestParams();
                // 设置image参数
                param.setImageFile(file);
                //  UploadFile.getInstance().uploadFileToBos(mContext, file);
                OCR.getInstance(mContext).recognizeLicensePlate(param, new OnResultListener<OcrResponseResult>() {
                    @Override
                    public void onResult(OcrResponseResult result) {
                        // 调用成功，返回OcrResponseResult对象
                        runOnUiThread(() -> {
                            dismissLoadingDialog();
                            number = new Gson().fromJson(result.getJsonRes(), LicenseTagBean.class).getWordsResult().getNumber();
                            if (!TextUtils.isEmpty(number)) {
                                ToastUtils.makeText(mContext, number, ToastUtils.LENGTH_SHORT).show();
                                Intent intent = new Intent();
                                intent.putExtra("License", number);
                                setResult(10, intent);
                                AppManager.getAppManager().finishActivity();
                            } else {
                                cameraView.start();
                                MobclickAgent.onEvent(mContext, "tapScanTagFailed");
                                ToastUtils.makeText(mContext, "识别失败，请重试", ToastUtils.LENGTH_SHORT).show();
                            }
                            MobclickAgent.onEvent(mContext, "tapScanTagSucceed");
                        });
                    }

                    @Override
                    public void onError(OCRError error) {
                        MobclickAgent.onEvent(mContext, "tapScanTagFailed");
                        Logger.i("CAMERA_DECODE", "失败" + error.getMessage());
                        cameraView.start();
                        runOnUiThread(() -> {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, "识别失败，请重试", ToastUtils.LENGTH_SHORT).show();
                        });
                    }
                });
            } else {
                GeneralBasicParams param = new GeneralBasicParams();
                param.setImageFile(file);
                // 调用通用文字识别服务
                OCR.getInstance(mContext).recognizeAccurateBasic(param, new OnResultListener<GeneralResult>() {
                    public void onResult(GeneralResult result) {
                        // 调用成功，返回OcrResponseResult对象
                        Logger.d("result===", result.toString());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dismissLoadingDialog();
                                TextScanTagBean textScanTagBean = new Gson().fromJson(result.getJsonRes(), TextScanTagBean.class);
                                if (textScanTagBean.getWords_result() != null && textScanTagBean.getWords_result().size() != 0) {
                                    number = new Gson().fromJson(result.getJsonRes(), TextScanTagBean.class).getWords_result().get(0).getWords();
                                }
                                if (!TextUtils.isEmpty(number)) {
                                    ToastUtils.makeText(mContext, number, ToastUtils.LENGTH_SHORT).show();
                                    Intent intent = new Intent();
                                    intent.putExtra("Text", number);
                                    setResult(11, intent);
                                    AppManager.getAppManager().finishActivity();
                                } else {
                                    cameraView.start();
                                    MobclickAgent.onEvent(mContext, "tapScanTagFailed");
                                    ToastUtils.makeText(mContext, "识别失败，请重试", ToastUtils.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }

                    @Override
                    public void onError(OCRError error) {
                        MobclickAgent.onEvent(mContext, "tapScanTagFailed");
                        Logger.i("TEXT_DECODE", "失败" + error.getMessage());
                        cameraView.start();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dismissLoadingDialog();
                                ToastUtils.makeText(mContext, "识别失败，请重试", ToastUtils.LENGTH_SHORT).show();
                            }
                        });
                    }
                });

            }
        });
    }

    private void initLightSenser() {
        //首先要获取SensorManager传感器管理器服务：
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        //获取光照传感器：
        Sensor liaghtSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);//Sensor.TYPE_LIGHT 代表光照传感器
        if (null != liaghtSensor) {
            //注册和监视光照传感器：
            //监视传感器的改变
            //accuracy 传感器的精度 通过event.accuracy获取
            //values 传感器传回的数值  如event.values[0] 获取光线强度lux
            //timestamp 传感器事件发生的时间（以纳秒为单位）
            //对传感器精度的改变做出反应
            Logger.i("LIGHT", "存在");
            sensorManager.registerListener(listener, liaghtSensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    private SensorEventListener listener = new SensorEventListener() {
        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            // values数组中第一个下标的值就是当前的光照强度
            float value = event.values[0];
            //Logger.i("LIGHT", value + "");
            if (value < 80) {
                llScanLight.setVisibility(View.VISIBLE);
            } else if (value >= 80 && !isLightOn) {
                llScanLight.setVisibility(View.INVISIBLE);
            }
        }

    };

    @OnClick({R.id.qr_code_header_back, R.id.ll_scan_light})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.qr_code_header_back:
                AppManager.getAppManager().finishActivity();
                break;
            case R.id.ll_scan_light:

                if (cameraView.getCameraControl().getFlashMode() == ICameraControl.FLASH_MODE_OFF) {
                    cameraView.getCameraControl().setFlashMode(ICameraControl.FLASH_MODE_TORCH);
                    ivScanLight.setImageDrawable(getResources().getDrawable(R.drawable.flashlight_open));
                    tvTip.setVisibility(View.VISIBLE);
                } else {
                    cameraView.getCameraControl().setFlashMode(ICameraControl.FLASH_MODE_OFF);
                    ivScanLight.setImageDrawable(getResources().getDrawable(R.drawable.flashlight));
                    tvTip.setVisibility(View.GONE);
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        cameraView.start();
    }

    @Override
    protected void onPause() {
        cameraView.stop();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (null != listener) {
            sensorManager.unregisterListener(listener);
        }
        CameraThreadPool.cancelAutoFocusTimer();
    }

    @Override
    public void onBackPressed() {
        AppManager.getAppManager().finishActivity();
    }
}
